<?php

class subscriber
{
	var $mul_db;			// Mullet DB connection
	var $smf_db;			// SMF DB connection
	var $error_source =		'subscriber';
	
	// Subscriber data
	var $sid =				NULL;
	var $uid =				NULL;
	var $char_name =		'';
	var $lvl =				0;
	var $class =			'';
	var $talent =			'';
	var $role =				'';
	var $comments =			'';
	var $status =			FALSE;
	var $used =				FALSE;
	var $sub_time =			'';
	var $email =			'';
	var $attended =			FALSE;

	// User's profile characters
	var $characters =		array();
	





	// Constructor
	function subscriber($mul_db, $smf_db, $subscriber_id = NULL)
	{
		$this->mul_db = $mul_db;
		$this->smf_db = $smf_db;

		// Retrieve subscriber information.
		if ($subscriber_id != NULL)
		{
			$this->sid = $subscriber_id;
			$this->getSubscriber();
		}
	}





	// Get subscriber data
	function getSubscriber()
	{
		global $mConfig;


		$sql_query = 'SELECT * FROM '.$mConfig['table_subscriptions'].' WHERE signup_id = '.$this->sid;
		$sql_result = mysql_query($sql_query, $this->mul_db) or
			die('There was an error querying the subscriber from Mullet. SQL: '.$sql_query);
		$sql_fetch = mysql_fetch_assoc($sql_result);

		$this->sid =			$sql_fetch['signup_id'];
		$this->uid =			$sql_fetch['user_id'];
		$this->char_name =		html_entity_decode($sql_fetch['char_name']);
		$this->lvl =			$sql_fetch['lvl'];
		$this->class =			stripslashes($sql_fetch['class']);
		$this->talent =			$sql_fetch['talent'];
		$this->role =			stripslashes($sql_fetch['role']);
		$this->comments =		stripslashes($sql_fetch['comments']);
		$this->status =			$sql_fetch['status'];
		$this->used =			$sql_fetch['attending'];
		$this->sub_time =		$sql_fetch['sub_time'];
		$this->email =			stripslashes($sql_fetch['email']);
		$this->attended =		$sql_fetch['attended'];
		
		unset($sql_query); mysql_free_result($sql_result); unset($sql_fetch);
	}





	// Add or update a subscriber.
	function setSubscriber($post)
	{
		global $errors, $mConfig;
		$n_subscriber = array();


		// Set array from passed variables.
		$n_subscriber['char_name'] = ucwords($post['user_char']);
		$n_subscriber['comments'] = sanatizeText($post['comment']);
		$n_subscriber['is_update'] = $post['is_update'];
		$n_subscriber['user_id'] = $this->getUsersID($n_subscriber['char_name']);
		$n_subscriber['event_id'] = $post['event_id'];
		$n_subscriber['role'] = $post['user_role'];
		$n_subscriber['status'] = $post['user_status'];





		// Check for blank or incorrect information.
		if ($n_subscriber['user_id'] == FALSE)
			$errors->addError($this->error_source, 'Could not query user ID from character name ('.$n_subscriber['char_name'].').');

		if (strlen($n_subscriber['char_name']) == 0)
		{
			// If it's empty, fill it so we can check for duplicate entries.
			$n_subscriber['char_name'] = '';
			$errors->addError($this->error_source, 'Character name was left blank.');
		}

		if ($n_subscriber['role'] == 'null')
			$errors->addError($this->error_source, 'A role was not selected.');

		if ($n_subscriber['status'] == 'null')
			$errors->addError($this->error_source, 'A status was not selected.');

		// Check for a duplicate entry using character name and the event ID.
		if ($n_subscriber['is_update'] == FALSE)
		{
			$sql_query = 'SELECT signup_id FROM '.$mConfig['table_subscriptions'].'
				WHERE char_name = "'.$n_subscriber['char_name'].'" AND event_id = '.$n_subscriber['event_id'];
			$sql_result = mysql_query($sql_query, $this->mul_db) or
				die('There was an error checking for duplicate subscriptions. SQL: '.$sql_query);
		
			if (mysql_num_rows($sql_result) > 0)
				$errors->addError($this->error_source, $n_subscriber['char_name'].' is already subscribed to that event.');
		}

		// If we found errors at any time, we're done here.
		if ($errors->error_count > 0) return FALSE;





		// Retrieve e-mail address.
		$sql_query = 'SELECT emailAddress FROM smf_members WHERE ID_MEMBER = '.$n_subscriber['user_id'];
		$sql_result = mysql_query($sql_query, $this->smf_db) or
			die('There was an error retrieving user\'s e-mail address. SQL: '.$sql_query);
		$sql_fetch = mysql_fetch_assoc($sql_result);

		$n_subscriber['email'] = $sql_fetch['emailAddress'];
		
		unset($sql_query); mysql_free_result($sql_result); unset($sql_fetch);





		// Connect to the Armory for latest character data.
		$armory = $this->getArmory($n_subscriber['char_name']);


		// Test the results from the Armory.
		if (in_array(NULL, $armory) or $armory == FALSE)
		{
			$armory = array();
			$this->getUsersCharacters($n_subscriber['user_id']);


			// Grab the character info from user's forum profile.
			foreach ($this->characters as $char_id)
			{
				if (strcasecmp($char_id['name'], $n_subscriber['char_name']) == 0)
				{
					$armory['class'] = $char_id['class'];
					$armory['level'] = $char_id['level'];
					$armory['talent'] = '0/0/0';
				}
			}

			unset($char_id);


			// Nothing found means they have no forum profile. Reject.
			if (count($armory) == 0)
			{
				$errors->addError($this->error_source, 'Character data for '.$n_subscriber['char_name'].' cannot be found.');
				return FALSE;
			}
		}


		// Verify character is Alliance on Kilrogg.
		else
		{
			if ($armory['faction'] != 'Alliance' or $armory['realm'] != 'Kilrogg')
			{
				$errors->addError($this->error_source, $n_subscriber['char_name'].' does not qualify for a subscription.');
				return FALSE;
			}
		}


		$n_subscriber['class'] = $armory['class'];
		$n_subscriber['lvl'] = $armory['level'];
		$n_subscriber['talent'] = $armory['talent'];





		if ($n_subscriber['is_update'] == FALSE)
		{
			$fields = "(`user_id`, `event_id`, `char_name`, `lvl`, `class`, `talent`,
				`role`, `comments`, `status`, `sub_time`, `email`)";

			$values = "(%d, %d, '%s', %d, '%s', '%s', '%s', '%s', %d, %d, '%s')";

			$sql_query = sprintf("INSERT INTO ".$mConfig['table_subscriptions']." ".$fields." VALUES ".$values,
					$n_subscriber['user_id'],
					$n_subscriber['event_id'],
					mysql_real_escape_string($n_subscriber['char_name'], $this->mul_db),
					mysql_real_escape_string($n_subscriber['lvl'], $this->mul_db),
					mysql_real_escape_string($n_subscriber['class'], $this->mul_db),
					mysql_real_escape_string($n_subscriber['talent'], $this->mul_db),
					mysql_real_escape_string($n_subscriber['role'], $this->mul_db),
					mysql_real_escape_string($n_subscriber['comments'], $this->mul_db),
					mysql_real_escape_string($n_subscriber['status'], $this->mul_db),
					mktime(),
					mysql_real_escape_string($n_subscriber['email'], $this->mul_db));
		}
		else
		{
			// User cannot become unvailable w/o supplying a reason.
			if ($n_subscriber['status'] == UNAVAILABLE and strlen($n_subscriber['comments']) == 0)
			{
				$errors->addError($this->error_source, 'You must supply a reason for becoming unavailable.');
				return FALSE;
			}


			$set = "lvl = %d, class = '%s', talent = '%s', role = '%s', comments = '%s', status = %d";


			$sql_query = sprintf("UPDATE ".$mConfig['table_subscriptions']." SET ".$set."
			WHERE event_id = %d AND char_name = '%s'",
				mysql_real_escape_string($n_subscriber['lvl'], $this->mul_db),
				mysql_real_escape_string($n_subscriber['class'], $this->mul_db),
				mysql_real_escape_string($n_subscriber['talent'], $this->mul_db),
				mysql_real_escape_string($n_subscriber['role'], $this->mul_db),
				mysql_real_escape_string($n_subscriber['comments'], $this->mul_db),
				mysql_real_escape_string($n_subscriber['status'], $this->mul_db),
				$n_subscriber['event_id'],
				mysql_real_escape_string($n_subscriber['char_name'], $this->mul_db));
		}

		mysql_query($sql_query, $this->mul_db);

		if (mysql_affected_rows($this->mul_db) == 0)
		{
			$errors->addError($this->error_source, 'There was an error adding the subscriber to Mullet. SQL: '.$sql_query);
			return FALSE;
		}

		unset($sql_query); mysql_free_result($sql_result); unset($sql_fetch);
	}





	// Get Armory data.
	function getArmory($char_name)
	{
		$character = array();

		$armory = new phpArmory();
		$char = $armory->characterFetch($char_name, 'Kilrogg');


		if (!$char) return FALSE;
		else
		{
			$character['class'] = $char['characterinfo']['character']['attributes']['class'];
			$character['level'] = $char['characterinfo']['character']['attributes']['level'];
			$character['realm'] = $char['characterinfo']['character']['attributes']['realm'];
			$character['faction'] = $char['characterinfo']['character']['attributes']['faction'];
			$character['talent'] = $char['characterinfo']['charactertab']['talentspec']['attributes']['treeone'].'/'.$char['characterinfo']['charactertab']['talentspec']['attributes']['treetwo'].'/'.$char['characterinfo']['charactertab']['talentspec']['attributes']['treethree'];
		}

		return $character;
	}





	// Get characters from user's forum profile.
	function getUsersCharacters($user_id)
	{
		global $mConfig;


		/**
		 * This is the order the character information is saved in the SMF database:
		 * 		char_name, char_level, char_guild, char_gender, char_race, char_class
		 * The person who wrote this forum mod sorta hacked it together.
		 */

		$sql_query = 'SELECT variable, value FROM smf_themes WHERE ID_MEMBER = '.$user_id.' AND variable LIKE "%char_%"';
		$sql_result = mysql_query($sql_query, $this->smf_db) or
			die('There was an error querying for user\'s characters. SQL: '.$sql_query);

		while ($sql_fetch = mysql_fetch_assoc($sql_result))
		{
			$index = substr($sql_fetch['variable'], -1, 1);			// the last character, which is the character ID
			$variable = substr($sql_fetch['variable'], 5, -1);		// char_variable# (5th char in, up to last character)

			// Don't add blank character data.
			if (trim($sql_fetch['value']) != '')
			{
				switch ($variable)
				{
					case 'name': 	$this->characters[$index]['name'] = 		htmlentities($sql_fetch['value']); break;
					case 'level': 	$this->characters[$index]['level'] = 		htmlentities($sql_fetch['value']); break;
					case 'guild': 	$this->characters[$index]['guild'] = 		htmlentities($sql_fetch['value']); break;
					case 'race': 	$this->characters[$index]['race'] = 		htmlentities($sql_fetch['value']); break;
					case 'class': 	$this->characters[$index]['class'] = 		htmlentities($sql_fetch['value']); break;
					case 'server':	$this->characters[$index]['server'] = 		htmlentities($sql_fetch['value']); break;
				}
			}
		}

		unset($sql_query); mysql_free_result($sql_result); unset($sql_fetch);


		// Pull out invalid characters and re-order the array.
		$horde = array('Blood Elf', 'Orc', 'Tauren', 'Troll', 'Undead');
		$new_index = 0;

		for ($i = 1; $i < (count($this->characters) + 1); $i++)
		{
			/**
			 *	Test for:
			 *		- Not on Kilrogg
			 *		- Horde character
			 *		- Not in Shinsei
			 */
			$is_valid = TRUE;

			if (strcasecmp($this->characters[$i]['server'], 'Kilrogg') != 0)	$is_valid = FALSE;
			if (in_array($this->characters[$i]['race'], $horde))				$is_valid = FALSE;
			if (strcasecmp($this->characters[$i]['guild'], 'Shinsei') != 0)		$is_valid = FALSE;


			// If all are valid, build the new character array.
			if ($is_valid == TRUE)
			{
				$this->characters[$new_index]['name'] = $this->characters[$i]['name'];
				$this->characters[$new_index]['level'] = $this->characters[$i]['level'];
				$this->characters[$new_index]['class'] = $this->characters[$i]['class'];


				// Set default role.
				$armory = $this->getArmory($this->characters[$i]['name']);

				if (in_array(NULL, $armory) or $armory == FALSE)
				{
					$this->characters[$new_index]['role'] = 'dm';
				}
				else
				{
					$trees = explode("/", $armory['talent']);
	
												$spec = 0;
					if ($trees[0] < $trees[1]) 	$spec = 1;
					if ($trees[1] < $trees[2]) 	$spec = 2;
		
					$this->characters[$new_index]['role'] =
						$mConfig['talentspec'][$this->characters[$i]['class']][$spec];
				}


				// Increment our new array counter.
				$new_index++;
			}

			unset($this->characters[$i]);
		}
		
		ksort($this->characters);
	}





	// Get user's ID from forum profile.
	function getUsersID($character)
	{
		$sql_query = 'SELECT ID_MEMBER FROM smf_themes WHERE value LIKE
			CONVERT( _utf8 "'.$character.'" USING latin1) COLLATE latin1_german2_ci';
		$sql_result = mysql_query($sql_query, $this->smf_db) or
			die('There was an error querying the SMF database for user ID. SQL: '.$sql_query);
		$sql_fetch = mysql_fetch_assoc($sql_result);
		
		return $sql_fetch['ID_MEMBER'];
	}





	// Set character status: attending.
	function setAttending($eid)
	{
		global $errors, $mConfig;


		if ($this->status != UNAVAILABLE)
		{
			// Set local status.
			($this->status == ATTENDING) ? $this->status = AVAILABLE : $this->status = ATTENDING;


			// Update this character's status on the database.
			$sql_query = sprintf("UPDATE %s SET status = %d WHERE signup_id = %d",
				$mConfig['table_subscriptions'], $this->status, $this->sid);
			mysql_query($sql_query, $this->mul_db);

			if (mysql_affected_rows($this->mul_db) == 0)
			{
				$errors->addError($this->error_source,
					'There was an error attending '.$this->char_name.' to the event. SQL: '.$sql_query);
			}

			unset($sql_query);
		}
		else
		{
			$errors->addError($this->error_source, $this->char_name.' is unavailable and cannot attend this event.');
		}
	}





	// Un-attend user's other characters.
	function unattendSurplusCharacters($users, $eid)
	{
		global $mConfig;


		foreach($users as $user_id => $subscribers)
		{
			$sql_query =
				'UPDATE '.$mConfig['table_subscriptions'].' SET status = '.AVAILABLE.' WHERE signup_id != '.$subscribers[0].'
				AND user_id = '.$user_id.' AND status = '.ATTENDING.' AND event_id = '.$eid;

			mysql_query($sql_query, $this->mul_db) or die('Could not un-attend surplus characters. SQL: '.$sql_query);

			unset($sql_query);
		}
		
		unset($user_id); unset($subscribers);
	}





	// Remove character from event.
	function removeFromEvent()
	{
		$sql_query = 'DELETE FROM subscriptions WHERE signup_id = '.$this->sid;

		mysql_query($sql_query, $this->mul_db) or
			die('Could not remove '.$this->char_name.' from this event. SQL: '.$sql_query);

		unset($sql_query);
	}

}
?>